//
//  KaoqinViewController.m
//  OA
//
//  Created by Admin on 2017/6/16.
//  Copyright © 2017年 yy. All rights reserved.
//

#import "KaoqinViewController.h"
#import "StatisticsViewController.h"
#import "FillCardViewController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
@interface KaoqinViewController ()<CLLocationManagerDelegate,TimeChouseDelegate,AMapLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *headImg;
@property (weak, nonatomic) IBOutlet UILabel *userName;
@property (weak, nonatomic) IBOutlet UILabel *headName;
// 上班打卡
@property (weak, nonatomic) IBOutlet UIImageView *sbImg; // 上班打卡图标
@property (weak, nonatomic) IBOutlet UILabel *sbTime; // 上班打卡时间
@property (weak, nonatomic) IBOutlet UILabel *ssbTime; // 上班应打卡时间
@property (weak, nonatomic) IBOutlet UIImageView *sbPorW; // 上班打卡地点或wifi图标
@property (weak, nonatomic) IBOutlet UILabel *sbPorWName;// 上班打卡地点或wifi名称
@property (weak, nonatomic) IBOutlet UIImageView *sbtype; // 上班打卡类型图标（正常、迟到、外勤）
@property (weak, nonatomic) IBOutlet UIView *shuxianView; // 上班灰色竖线
@property (weak, nonatomic) IBOutlet UILabel *sbjtw;


//已经下班打卡
@property (weak, nonatomic) IBOutlet UIView *axbView; // 已经下班打卡view
@property (weak, nonatomic) IBOutlet UILabel *axbTime; // 下班打卡时间
@property (weak, nonatomic) IBOutlet UILabel *sxbTime; // 下班应打卡时间
@property (weak, nonatomic) IBOutlet UIImageView *xbPorW;// 下班打卡地点或wifi图标
@property (weak, nonatomic) IBOutlet UILabel *xbPorWName;// 下班打卡地点或wifi名称
@property (weak, nonatomic) IBOutlet UIImageView *xbtype;

// 下班打卡view
@property (weak, nonatomic) IBOutlet UIView *xbView;
@property (weak, nonatomic) IBOutlet UILabel *ssxbTime; // 下班应打卡时间
@property (weak, nonatomic) IBOutlet UILabel *xbjtw;

// 打卡view
@property (weak, nonatomic) IBOutlet UIView *dkView;
@property (weak, nonatomic) IBOutlet UIImageView *dkImg; // 打卡外圈圆
@property (weak, nonatomic) IBOutlet UIButton *dkButton; //打卡手指


@property (weak, nonatomic) IBOutlet UILabel *porwName;
@property (weak, nonatomic) IBOutlet UILabel *date;
@property (nonatomic, strong) NSDictionary *data;
@property (nonatomic ,strong) NSString *currentDateString; // 当前日期
@property (nonatomic ,strong)CABasicAnimation* rotationAnimation;
@property (nonatomic ,assign)CGFloat longitude;
@property (nonatomic ,assign)CGFloat latitude;


@property (nonatomic ,assign) CGFloat kilo; // 距离
@property (weak, nonatomic) IBOutlet UILabel *kaoqinType; // 考勤类型

@property (weak, nonatomic) IBOutlet UIView *dkcgView;// 打卡成功弹出框
@property (weak, nonatomic) IBOutlet UIImageView *cgView;// 成功背景
@property (weak, nonatomic) IBOutlet UILabel *dkshijian; // 成功打卡时间
@property (weak, nonatomic) IBOutlet UILabel *cgJtw;

@property (weak, nonatomic) IBOutlet UIButton *gengxinButton;
@property (nonatomic ,strong) NSString *dateStr;
@property (nonatomic ,strong) BasisChooseTimeView *viewOfData;

@property (nonatomic ,strong) NSArray *dkAddress; // 打卡地点数组
@property (nonatomic ,strong) NSArray *longitudeArr; // 打卡经度数组
@property (nonatomic ,strong) NSArray *latitudeArr; // 打卡纬度数组

@property (nonatomic ,strong)AMapLocationManager *locationManager;
@property (nonatomic, assign) BOOL locatingWithReGeocode;

@property (nonatomic ,strong) NSString *dkAddressName; // 打卡定位位置
@end

@implementation KaoqinViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"考勤";
    self.dkAddressName = @"";
    self.xbView.hidden = NO;
    self.axbView.hidden = YES;
    self.shuxianView.hidden = YES;
    self.dkcgView.hidden = YES;
    self.gengxinButton.hidden = YES;
    self.gengxinButton.layer.borderColor = [UIColor getColorWithHexString:@"3EACE8"].CGColor;
    self.gengxinButton.layer.borderWidth = 1;
    self.gengxinButton.layer.cornerRadius = 5;
    self.gengxinButton.clipsToBounds = YES;
    self.kilo = 1000;
    if (Y_mainW < 370) {
       self.headImg.layer.cornerRadius = 32.5 / 2;
    } else if(Y_mainW < 400){
       self.headImg.layer.cornerRadius = 40 / 2;
    } else {
        self.headImg.layer.cornerRadius = 45.33 / 2;
    }
//    self.headImg.layer.cornerRadius = 40 / 2;
    self.headImg.clipsToBounds = YES;
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设置格式：
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    //NSDate转NSString
    self.currentDateString = [dateFormatter stringFromDate:date];
    self.dateStr = [dateFormatter stringFromDate:date];;
    self.date.text = [self.dateStr substringToIndex:10];
    [self getData];
    self.rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    self.rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    self.rotationAnimation.duration = 0.5;
    self.rotationAnimation.cumulative = YES;
    self.rotationAnimation.repeatCount = HUGE_VALF;
    [self.dkImg.layer addAnimation:self.rotationAnimation forKey:@"rotationAnimation"];
    
    
    // 高德持续定位
    [AMapServices sharedServices].apiKey =@"f91e5c264b49b420c54c09aefe4a5795";
    
    
    
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.distanceFilter = 5;
    [self.locationManager startUpdatingLocation];
//    //开启定位
//    CLLocationManager *manager = [ShareUserInfo shaCLLocationManager];
//    //f91e5c264b49b420c54c09aefe4a5795
//    //设置代理
//    manager.delegate=self;
//    //设置定位精度
//    manager.desiredAccuracy=kCLLocationAccuracyBest;
//    //定位频率,每隔多少米定位一次
//    CLLocationDistance distance = 1.0;//10米定位一次
//    manager.distanceFilter=distance;
    //启动跟踪定位
//    [manager startUpdatingLocation];
}
//oa_getTodayAttendance
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    if (self.timer != nil) {
//        dispatch_cancel(self.timer);
//        self.timer = nil;
//    }
    
}
-(void)viewWillAppear: (BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tabBarController.tabBar setHidden:YES];
}
- (IBAction)choiceDate:(id)sender {
    [self.view addSubview:self.viewOfData];
}
#pragma mark -- 更新打卡
- (IBAction)gengxindaka:(id)sender {
    
    
    NSString *beginStatus = self.data[@"beginStatus"];
    
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设置格式：
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    self.currentDateString = [dateFormatter stringFromDate:date];
    NSString *beginSet = self.data[@"begintimeSet"];
    NSString *endSet = self.data[@"endtimeSet"];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *nowDate = [dateFormatter dateFromString:self.currentDateString];
    // 需要对比的时间数据
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
    | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    
    NSDictionary *dic;
    
        NSDate *expireDate = [dateFormatter dateFromString:[endSet substringToIndex:18]];
        NSString *str = [dateFormatter stringFromDate:expireDate];
        // 对比时间差
        NSDateComponents *dateCom = [calendar components:unit fromDate:nowDate toDate:expireDate options:0];
        NSLog(@"%d",dateCom.second);
        NSInteger second = 0; // 相差的时间
        second = second + dateCom.second;
        second = second + dateCom.minute * 60;
        second = second + dateCom.hour * 3600;
        if ([self.currentDateString compare: endSet]  < 0) {
            
        }
        dic = @{@"datenumber":[self.currentDateString substringToIndex:10],
                @"endtime":self.currentDateString,
                @"earlyTime":[self.currentDateString compare: endSet]  < 0 ?[NSString stringWithFormat:@"%d",labs(second)] : @"0",
                @"endAddress":self.kilo < 300 ? self.porwName.text : self.dkAddressName,
                @"endType":self.kilo < 300 ? @"0" : @"1",
                @"endStatus":[self.currentDateString compare: endSet]  > 0 ? @"1" : @"2",
                @"endNote":@""
                };
        
        Y_Wait
        [[ToolOfNetWork sharedTools] YrequestURL:oa_saveAttendanceByEnd withParams:dic.mutableCopy finished:^(id responsObject, NSError *error) {
            Y_Hide
            if (_Success) {
                dispatch_cancel([ShareUserInfo sharedUserInfo].timer);
                [ShareUserInfo sharedUserInfo].timer = nil;
                [self getData];
                NSString *begintime = dic[@"endtime"];
                self.dkshijian.text = [NSString stringWithFormat:@"打卡时间：%@",[begintime substringWithRange:NSMakeRange(11, 8)]];
                if ([dic[@"endStatus"] isEqualToString:@"1"]) {
                    if ([dic[@"endType"] isEqualToString:@"0"]) {
                        [self.cgView setImage:[UIImage imageNamed:@"打卡成功背景"]];
                    } else {
                        [self.cgView setImage:[UIImage imageNamed:@"外勤背景"]];
                    }
                } else {
                    [self.cgView setImage:[UIImage imageNamed:@"迟到打卡背景"]];
                }
                self.dkcgView.hidden = NO;
            } else {
                [MBProgressHUD showError:responsObject[@"message"]];
            }
            NSLog(@"%@",[[responsObject description]kdtk_stringByReplaceingUnicode]);
            NSLog(@"%@",error.localizedDescription);
        }];
    
}
- (void)getData {
    NSDictionary *dic = @{@"datenumber":self.dateStr};
    Y_Wait
    [[ToolOfNetWork sharedTools] YrequestURL:oa_getTodayAttendance withParams:dic.mutableCopy finished:^(id responsObject, NSError *error) {
        Y_Hide
        if (_Success) {
//            NSLog(@"%@",responsObject[@"data"]);
            self.data = responsObject[@"data"];
            self.dkAddress = [self.data[@"punchpoint"] componentsSeparatedByString:@";"];
            self.longitudeArr = [self.data[@"longitude"] componentsSeparatedByString:@";"];
            self.latitudeArr = [self.data[@"latitude"] componentsSeparatedByString:@";"];
            [self loadUI];
            [self time];
        } else {
            [MBProgressHUD showError:responsObject[@"message"]];
        }
        NSLog(@"%@",[[responsObject description]kdtk_stringByReplaceingUnicode]);
        NSLog(@"%@",error.localizedDescription);
    }];
    
}
- (void)time {
//    self.data[@"endStatus"] = @"2017-08-01 11:09:60";
    NSTimeInterval period = 1.0; //设置时间间隔
    dispatch_queue_t queue = dispatch_get_main_queue();
    [ShareUserInfo sharedUserInfo].timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
    uint64_t interval = (uint64_t)(period * NSEC_PER_SEC);
    dispatch_source_set_timer([ShareUserInfo sharedUserInfo].timer, start, interval, 0);
    
    // 设置回调
    dispatch_source_set_event_handler([ShareUserInfo sharedUserInfo].timer, ^{
//        NSLog(@"------------%@", [NSThread currentThread]);
        NSDate *date = [NSDate date];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设置格式：
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        self.currentDateString = [dateFormatter stringFromDate:date];
        NSInteger beginType = [self.data[@"beginStatus"] integerValue];
        NSInteger endType = [self.data[@"endStatus"] integerValue];
        NSString *beginStr = self.data[@"begintimeSet"];
        NSString *endStr = self.data[@"endtimeSet"];
//        endStr = @"2017-08-01 11:09:60";
        if (beginType == 0) {
            if ([self.currentDateString compare: beginStr]  > 0) {
//                dispatch_cancel(self.timer);
                [self.dkImg setImage:[UIImage imageNamed:@"迟到点击环"]];
                [self.dkButton setBackgroundImage:[UIImage imageNamed:@"点迟点击"] forState:UIControlStateNormal];
            } else {
                if (self.kilo < 300) {
                    [self.dkImg setImage:[UIImage imageNamed:@"打卡点击环"]];
                    [self.dkButton setBackgroundImage:[UIImage imageNamed:@"打卡点击"] forState:UIControlStateNormal];
                } else {
                    [self.dkImg setImage:[UIImage imageNamed:@"外勤点击环"]];
                    [self.dkButton setBackgroundImage:[UIImage imageNamed:@"外勤点击"] forState:UIControlStateNormal];
                }
            }
        } else {
            if (endType == 0) {
                if ([self.currentDateString compare: endStr]  < 0) {
                    [self.dkImg setImage:[UIImage imageNamed:@"迟到点击环"]];
                    [self.dkButton setBackgroundImage:[UIImage imageNamed:@"点迟点击"] forState:UIControlStateNormal];
                } else {
                    if (self.kilo < 300) {
                        [self.dkImg setImage:[UIImage imageNamed:@"打卡点击环"]];
                        [self.dkButton setBackgroundImage:[UIImage imageNamed:@"打卡点击"] forState:UIControlStateNormal];
                    } else {
                        [self.dkImg setImage:[UIImage imageNamed:@"外勤点击环"]];
                        [self.dkButton setBackgroundImage:[UIImage imageNamed:@"外勤点击"] forState:UIControlStateNormal];
                    }
//                    [self.dkImg setImage:[UIImage imageNamed:@"打卡点击环"]];
//                    [self.dkButton setBackgroundImage:[UIImage imageNamed:@"打卡点击"] forState:UIControlStateNormal];
                }
            }
        }
    });
     dispatch_resume([ShareUserInfo sharedUserInfo].timer);
}
- (void)loadUI {
    NSDictionary *dic = self.data;
    self.userName.text = dic[@"username"];
    NSString *nameStr = dic[@"username"];
    self.kaoqinType.text = dic[@"team"];
    self.headName.text = [nameStr substringWithRange:NSMakeRange(nameStr.length - 2, 2)];
    self.ssbTime.text = [NSString stringWithFormat:@"(上班时间%@)",[dic[@"begintimeSet"] substringWithRange:NSMakeRange(11, 8)]];
    self.sxbTime.text =[NSString stringWithFormat:@"(下班时间%@)",[dic[@"endtimeSet"] substringWithRange:NSMakeRange(11, 8)]];
    self.ssxbTime.text =[NSString stringWithFormat:@"(下班时间%@)",[dic[@"endtimeSet"] substringWithRange:NSMakeRange(11, 8)]];
    NSInteger beginType = [dic[@"beginStatus"] integerValue];
//    self.date.text = [dic[@"datenumber"] substringToIndex:10];
    
    
    
    switch (beginType) {
        case 0:
            [self sbwdk];
            break;
        case 1:
            [self sbcddk];
            break;
        case 2:
            [self sbcddk];
            break;
        case 3:
            [self sbwdk];
            break;
        default:
            break;
    }
    if ([self.data[@"beginStatus"] isEqualToString:@"迟到"]) {
        [self sbcddk];
    }

    
}
#pragma mark -- 上班未打卡
- (void)sbwdk {
    self.sbTime.text = @"";
    self.sbPorWName.text = @"";
    [self.sbtype setImage:[UIImage imageNamed:@""]];
    self.sbPorW.hidden = YES;
    self.axbTime.text = @"";
    self.xbPorWName.text = @"";
    self.sbjtw.text = @"";
    self.dkView.hidden = NO;
    self.xbView.hidden = YES;
    self.axbView.hidden = YES;
    self.shuxianView.hidden = YES;
    self.porwName.hidden = NO;
}
#pragma mark -- 上班正常打卡
- (void)sbzcdk {
    self.sbTime.text = self.data[@"begintime"];
    self.sbPorWName.text = self.data[@"beginAddress"];
    [self.sbtype setImage:[UIImage imageNamed:@"正常"]];
//    [self.sbPorW setImage:[UIImage imageNamed:@""]];
    self.axbTime.text = @"";
    self.xbPorWName.text = @"";
    self.sbjtw.text = self.data[@"chickenSoup"];
    self.dkView.hidden = NO;
    self.xbView.hidden = NO;
    self.axbView.hidden = YES;
    self.shuxianView.hidden = YES;
    self.porwName.hidden = NO;
    
    [self pdxbk];
}
#pragma mark -- 上班正常、迟到打卡
- (void)sbcddk {
    self.sbTime.text = [NSString stringWithFormat:@"打卡时间%@",[self.data[@"begintime"] substringWithRange:NSMakeRange(11, 8)]];
    self.sbPorWName.text = self.data[@"beginAddress"];
    NSInteger beginStatus = [self.data[@"beginStatus"] integerValue];
    NSInteger beginType = [self.data[@"beginType"] integerValue];
    if (beginStatus == 1) {
        if (beginType == 1) {
            [self.sbtype setImage:[UIImage imageNamed:@"外勤"]];
        } else {
            [self.sbtype setImage:[UIImage imageNamed:@"正常"]];
        }
       
    } else {
        [self.sbtype setImage:[UIImage imageNamed:@"迟到"]];
    }
    //    [self.sbPorW setImage:[UIImage imageNamed:@""]];
    self.axbTime.text = @"";
    self.xbPorWName.text = @"";
    self.sbjtw.text = [self.data[@"chickenSoup"] componentsSeparatedByString:@"-"][0];
    self.dkView.hidden = NO;
    self.xbView.hidden = NO;
    self.axbView.hidden = YES;
    self.shuxianView.hidden = NO;
    self.porwName.hidden = NO;
    self.sbPorW.hidden = NO;
//    self.sbPorWName.hidden
    
    [self pdxbk];
}
#pragma mark -- 上班缺卡
- (void)sbqk {
    
    [self pdxbk];
}

#pragma mark -- 已经打了上班卡，判断下班卡
- (void)pdxbk {
    NSInteger type;
    NSString *endStatus = self.data[@"endStatus"];
     if (endStatus == nil || [endStatus isKindOfClass:[NSNull class]] || endStatus.length == 0){
         type = 0;
     } else {
         type = [self.data[@"endStatus"] integerValue];
     }
    
    switch (type) {
        case 0:
            [self xbdk];
            break;
        case 1:
            [self xbzcdk];
            break;
        case 2:
            [self xbzcdk];
            break;
        case 3:
            [self xbdk];
            break;
        default:
            break;
    }
}
#pragma mark -- 下班未打卡
- (void)xbdk {
    
}
#pragma mark -- 下班正常打卡
- (void)xbzcdk {
    self.axbTime.text = [NSString stringWithFormat:@"打卡时间%@",[self.data[@"endtime"] substringWithRange:NSMakeRange(11, 8)]];
    self.xbPorWName.text = self.data[@"endAddress"];
    NSInteger endStatus = [self.data[@"endStatus"] integerValue];
    NSInteger endType = [self.data[@"endType"] integerValue];
    if (endStatus == 1) {
        if (endType == 1) {
            [self.xbtype setImage:[UIImage imageNamed:@"外勤"]];
        } else {
           [self.xbtype setImage:[UIImage imageNamed:@"正常"]];
        }
        
        self.gengxinButton.hidden = YES;
    } else {
        [self.xbtype setImage:[UIImage imageNamed:@"早退"]];
        NSComparisonResult res =   [self.date.text compare:[self.currentDateString substringToIndex:10]];
        if (res == NSOrderedAscending )
        {
            self.gengxinButton.hidden = YES;
            return;
        }else if (res == NSOrderedDescending)
        {
            self.gengxinButton.hidden = YES;
            return;
        } else {
            self.gengxinButton.hidden = NO;
        }
        
    }
    self.dkView.hidden = YES;
    self.axbView.hidden = NO;
    self.xbView.hidden = YES;
    self.xbjtw.text = [self.data[@"chickenSoup"] componentsSeparatedByString:@"-"][1];
    self.porwName.hidden = YES;
}
#pragma mark -- 下班早退打卡
- (void)xbztdk {
    
}
#pragma mark -- 下班缺卡
- (void)xbqk {
    
}
#pragma mark -- 打卡
- (IBAction)dk:(id)sender {
    NSComparisonResult res =   [self.date.text compare:[self.currentDateString substringToIndex:10]];
    if (res == NSOrderedAscending )
    {
        [MBProgressHUD showError:@"请申请补卡"];
        return;
    }else if (res == NSOrderedDescending)
    {
        [MBProgressHUD showError:@"无法打卡"];
        return;
    }
    
    NSString *beginStatus = self.data[@"beginStatus"];
    
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设置格式：
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    self.currentDateString = [dateFormatter stringFromDate:date];
    NSString *beginSet = self.data[@"begintimeSet"];
    NSString *endSet = self.data[@"endtimeSet"];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *nowDate = [dateFormatter dateFromString:self.currentDateString];
    // 需要对比的时间数据
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
    | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    
    NSDictionary *dic;
    if ([beginStatus isEqualToString:@"0"]) {
        NSDate *expireDate = [dateFormatter dateFromString:[beginSet substringToIndex:beginSet.length - 2]];
        // 对比时间差
        NSDateComponents *dateCom = [calendar components:unit fromDate:nowDate toDate:expireDate options:0];
        NSLog(@"%d",dateCom.second);
        NSInteger second = 0; // 相差的时间
        second = second + dateCom.second;
        second = second + dateCom.minute * 60;
        second = second + dateCom.hour * 3600;
        dic = @{@"datenumber":[self.currentDateString substringToIndex:10],
                @"begintime":self.currentDateString,
                @"lateTime":[self.currentDateString compare: beginSet]  > 0 ?[NSString stringWithFormat:@"%d",labs(second)] : @"0",
                @"beginAddress": self.kilo < 300 ? self.porwName.text:self.dkAddressName,
                @"beginType":self.kilo > 300 ? @"1" : @"0",
                @"beginStatus":[self.currentDateString compare:[beginSet substringToIndex:beginSet.length - 2]] < 0 ? @"1":@"2" ,
                @"beginNote":@""
                };
        Y_Wait
        [[ToolOfNetWork sharedTools] YrequestURL:oa_saveAttendanceByBegin withParams:dic.mutableCopy finished:^(id responsObject, NSError *error) {
            Y_Hide
            if (_Success) {
                [self getData];
                NSString *begintime = dic[@"begintime"];
                self.dkshijian.text = [NSString stringWithFormat:@"打卡时间：%@",[begintime substringWithRange:NSMakeRange(11, 8)]];
                if ([dic[@"beginStatus"] isEqualToString:@"1"]) {
                    if ([dic[@"beginType"] isEqualToString:@"0"]) {
                        [self.cgView setImage:[UIImage imageNamed:@"打卡成功背景"]];
                    } else {
                        [self.cgView setImage:[UIImage imageNamed:@"外勤背景"]];
                    }
                } else {
                    [self.cgView setImage:[UIImage imageNamed:@"迟到打卡背景"]];
                }
                self.dkcgView.hidden = NO;
            } else {
                
                [MBProgressHUD showError:responsObject[@"message"]];
            }
            NSLog(@"%@",[[responsObject description]kdtk_stringByReplaceingUnicode]);
            NSLog(@"%@",error.localizedDescription);
        }];
    } else {
        NSDate *expireDate = [dateFormatter dateFromString:[endSet substringToIndex:18]];
        NSString *str = [dateFormatter stringFromDate:expireDate];
        // 对比时间差
        NSDateComponents *dateCom = [calendar components:unit fromDate:nowDate toDate:expireDate options:0];
        NSLog(@"%d",dateCom.second);
        NSInteger second = 0; // 相差的时间
        second = second + dateCom.second;
        second = second + dateCom.minute * 60;
        second = second + dateCom.hour * 3600;
        if ([self.currentDateString compare: endSet]  < 0) {
            
        }
        dic = @{@"datenumber":[self.currentDateString substringToIndex:10],
                @"endtime":self.currentDateString,
                @"earlyTime":[self.currentDateString compare: endSet]  < 0 ?[NSString stringWithFormat:@"%d",labs(second)] : @"0",
                @"endAddress":self.kilo < 300 ? self.porwName.text : self.dkAddressName,
                @"endType":self.kilo < 300 ? @"0" : @"1",
                @"endStatus":[self.currentDateString compare: endSet]  > 0 ? @"1" : @"2",
                @"endNote":@""
                };
        
        Y_Wait
        [[ToolOfNetWork sharedTools] YrequestURL:oa_saveAttendanceByEnd withParams:dic.mutableCopy finished:^(id responsObject, NSError *error) {
            Y_Hide
            if (_Success) {
                dispatch_cancel([ShareUserInfo sharedUserInfo].timer);
                [ShareUserInfo sharedUserInfo].timer = nil;
                [self getData];
                NSString *begintime = dic[@"endtime"];
                self.dkshijian.text = [NSString stringWithFormat:@"打卡时间：%@",[begintime substringWithRange:NSMakeRange(11, 8)]];
                if ([dic[@"endStatus"] isEqualToString:@"1"]) {
                    if ([dic[@"endType"] isEqualToString:@"0"]) {
                        [self.cgView setImage:[UIImage imageNamed:@"打卡成功背景"]];
                    } else {
                        [self.cgView setImage:[UIImage imageNamed:@"外勤背景"]];
                    }
                } else {
                    [self.cgView setImage:[UIImage imageNamed:@"迟到打卡背景"]];
                }
                self.dkcgView.hidden = NO;
            } else {
                [MBProgressHUD showError:responsObject[@"message"]];
            }
            NSLog(@"%@",[[responsObject description]kdtk_stringByReplaceingUnicode]);
            NSLog(@"%@",error.localizedDescription);
        }];
    }
    
    

}
- (IBAction)kaoqintongji:(id)sender {
    StatisticsViewController *vc = VCInSB(@"StatisticsViewController", @"ThirdViewControllers");
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)buka:(id)sender {
    NSComparisonResult res =   [self.date.text compare:[self.currentDateString substringToIndex:10]];
    if (res == NSOrderedAscending )
    {
        FillCardViewController *vc = VCInSB(@"FillCardViewController", @"FirstViewControllers");
        vc.dateStr = self.dateStr;
        if ([self.data[@"beginStatus"] isEqualToString:@"3"]) {
            vc.type = @"0";
            vc.bkTimeStr = [self.data[@"begintimeSet"] substringWithRange:NSMakeRange(11, 8)];
        } else if([self.data[@"endStatus"] isEqualToString:@"3"]){
            vc.bkTimeStr = [self.data[@"endtimeSet"] substringWithRange:NSMakeRange(11, 8)];
            vc.type = @"1";
        } else {
            [MBProgressHUD showError:@"无需申请补卡"];
            return;
        }
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [MBProgressHUD showError:@"当前日期无法补卡"];
        return;
    }
    
}
#pragma mark————————————定位后得到的数据

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *location=[locations firstObject];//取出第一个位置
    CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标
    NSLog(@"经度：%f,纬度：%f,海拔：%f,航向：%f,行走速度：%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
    //创建位置
    CLGeocoder *revGeo = [[CLGeocoder alloc] init];
    [revGeo reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if (!error && [placemarks count] > 0)
        {
            [_dkImg.layer removeAllAnimations];
            NSDictionary *dict =
            [[placemarks objectAtIndex:0] addressDictionary];
            NSLog(@"street address: %@", [dict objectForKey:@"Name"]);
            self.longitude = coordinate.longitude;
            self.latitude = coordinate.latitude;
            //
            CLLocationDistance kilometers = 1000;
            for (NSInteger index = 0; index < self.dkAddress.count; index ++) {
                CGFloat kqlongitude = [self.data[@"longitude"] floatValue];
                CGFloat kqlatitude = [self.data[@"latitude"] floatValue];
                CLLocation *orig=[[CLLocation alloc] initWithLatitude:kqlatitude  longitude:kqlongitude];
                CLLocation* dist=[[CLLocation alloc] initWithLatitude:self.latitude longitude:self.longitude];
                kilometers=[orig distanceFromLocation:dist];
                NSLog(@"%f-----%f",self.longitude,self.latitude);
                if (kilometers < 300) {
                    self.porwName.text = [dict objectForKey:@"FormattedAddressLines"][0];
                    self.kilo = kilometers;
                    break;
                    
                }
                NSLog(@"%f",kilometers);
                
            }
            if (self.kilo > 300) {
               self.porwName.text = @"当前不在考勤范围内";
            }
            
            NSLog(@"%@",dict);
        }
        else
        {
            NSLog(@"ERROR: %@", error);
        }
        
    }];
    
    
    
}


#pragma mark -- 高德定位
//- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location
//{
//    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
//    
//    
//}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode
{
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    self.longitude = location.coordinate.longitude;
    self.latitude = location.coordinate.latitude;
    CLGeocoder * geocoder = [[CLGeocoder alloc]init];
    
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error == nil && [placemarks count] > 0) {
            //这时的placemarks数组里面只有一个元素
            CLPlacemark * placemark = [placemarks firstObject];
            NSLog(@"%@",placemark.addressDictionary); //根据经纬度会输出该经纬度下的详细地址  国家 地区 街道 之类的
            [_dkImg.layer removeAllAnimations];
            NSDictionary *dict =
            [[placemarks objectAtIndex:0] addressDictionary];
            NSLog(@"street address: %@", [dict objectForKey:@"Name"]);
            self.dkAddressName = placemark.addressDictionary[@"FormattedAddressLines"][0];
            //
            CLLocationDistance kilometers = 1000;
            for (NSInteger index = 0; index < self.dkAddress.count; index ++) {
                CGFloat kqlongitude = [self.longitudeArr[index] floatValue];
                CGFloat kqlatitude = [self.latitudeArr[index] floatValue];
                CLLocation *orig=[[CLLocation alloc] initWithLatitude:kqlatitude  longitude:kqlongitude];
                CLLocation* dist=[[CLLocation alloc] initWithLatitude:self.latitude longitude:self.longitude];
                kilometers=[orig distanceFromLocation:dist];
                NSLog(@"%f-----%f",self.longitude,self.latitude);
                NSLog(@"---------%f",kilometers);
                if (kilometers < 300) {
                    self.porwName.text = self.dkAddress[index];
                    self.kilo = kilometers;
                    break;
                    
                }
                NSLog(@"%f",kilometers);
                
            }
            if (self.kilo > 300) {
                self.porwName.text = @"当前不在考勤范围内";
            }
            
            NSLog(@"%@",dict);
        }
    }];

}
- (NSString *)dateOfDidSelect:(NSString *)str{
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设置格式：
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *sssdate = [dateFormatter stringFromDate:date];
    self.date.text = str;
    self.dateStr = str;
    [self getData];
    if (![str isEqualToString:sssdate]) {
        [[ShareUserInfo shaCLLocationManager] stopUpdatingHeading];
        if (self.dkImg.layer.animationKeys.count > 0) {
            [self.dkImg.layer removeAllAnimations ];
        }
    } else {
       [[ShareUserInfo shaCLLocationManager] startUpdatingHeading];
        if (!self.dkImg.layer.animationKeys.count) {
//            [self.dkImg.layer addAnimation:self.rotationAnimation forKey:@"rotationAnimation"];
        }
        
    }
    [_viewOfData removeFromSuperview];
    return str;
}

- (void)removeBasisChooseTimeView {
    [_viewOfData removeFromSuperview];
}
-(UIView *)viewOfData{
    if (!_viewOfData) {
        
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"BasisChooseTimeView" owner:self options:nil];
        _viewOfData = (BasisChooseTimeView *)[nib objectAtIndex:0];
        _viewOfData.frame = CGRectMake(30, 30, Y_mainW-60, 280);
        _viewOfData.center = self.view.center;
        _viewOfData.layer.cornerRadius = 20;
        _viewOfData.layer.borderWidth = 0.2;
        _viewOfData.delegateOfTime = self;
        _viewOfData.isPrecision = NO;
        
    }
    return _viewOfData;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.dkcgView.hidden = YES;
}
@end
